<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportToExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop:'timeOfEntry', order:'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <!-- 添加显示用户头像 -->
          <el-table-column label="用户头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100%">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formatHireType(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)
                "
              >
                查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 3, 4, 8]"
            :page-size="size"
            layout="total,sizes,prev,pager,next,jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <addOrEdit ref="myEmp" @success="hSuccess" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
// 枚举
import employeesEnum from '@/constant/employees'
// 弹层组件
import addOrEdit from './empDialog.vue'
// 第二种
const hireType = {}
employeesEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
// 枚举的第三种方法
// const hireType = employeesEnum.hireType.reduce((acc, item) => {
//   acc[item.id] = item.value
// })
export default {
  components: {
    addOrEdit
  },
  data() {
    return {
      showDialog: false,
      list: [],
      page: 1, // 页码值
      size: 5, // 每页显示条数
      total: 0 // 总条数
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    exportToExcel() {
      const { tHeader, result } = this.formatToExcel(this.list)
      console.log(tHeader, 'tHeader')
      console.log(result, 'result')
      // 3.调用admin提供的函数 将数据写入excel
      import('@/vendor/Export2Excel').then(excel => {
        // 格式化数据
        excel.export_json_to_excel({
          header: tHeader,
          data: result,
          filename: '',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // 格式化excel的数据格式
    formatToExcel(list) {
      // 中英文的映射对象
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map(en_key => {
        return mapInfo[en_key]
      })
      // 2.生成标的内容data
      const result = list.map(item => {
        return Object.values(item)
      })
      return { tHeader, result }
    },
    // 删除功能
    async hDel(id) {
      this.$confirm('确认删除吗').then(async() => {
        const res = await delEmployee(id)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        if (res.data.code === 10000) {
          this.loadEmployeeList()
        }
      }).catch(err => console.log(err))
    },
    // 关闭弹窗
    hClose() {
      // 重置表单
      this.$refs.myEmp.resetForm()
    },
    // 关闭弹窗 重新渲染
    hSuccess() {
      // 数据加一
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.showDialog = false
      this.loadEmployeeList()
    },
    async loadEmployeeList() {
      try {
        const { data } = await getEmployeeList(this.page, this.size)
        console.log('获取角色数据1111', data)
        // 保存数据
        this.list = data.data.rows
        this.total = data.data.total
      } catch (err) {
        console.log(err)
      }
    },
    // 点击每页显示条数
    handleSizeChange(val) {
      this.page = 1
      this.size = val
      this.loadEmployeeList()
    },
    // 点击第几页
    handleCurrentChange(val) {
      this.page = val
      this.loadEmployeeList()
    },
    // 格式化聘用数据显示问题
    formatHireType(value) {
      // const obj = employeesEnum.hireType.find(item => item.id === value)
      return hireType[value] || '未知'
    }
  }
}
</script>

<style>
</style>
